<template>
  <Dialog
    :title="t('fileObjectDownload.title')"
    v-model="dialogVisible"
    width="80%"
    top="2vh"
    style="margin-bottom: 0"
  >
    <div v-loading="loading" class="w-full" style="height: 80vh">
      <el-scrollbar height="80vh" wrap-style="padding: 0 8px">
        <VuePdfEmbed v-if="url" :source="url" :annotation-layer="false" :text-layer="false" />
        <div v-else class="p-10px text-center">{{ t('fileObjectDownload.noFile') }}</div>
      </el-scrollbar>
      <!--      <embed-->
      <!--        v-if="url"-->
      <!--        width="100%"-->
      <!--        height="100%"-->
      <!--        :src="url"-->
      <!--        type="application/pdf"-->
      <!--        style="height: 100%"-->
      <!--      />-->
    </div>
  </Dialog>
</template>

<script setup lang="ts">
import VuePdfEmbed from 'vue-pdf-embed'
import 'vue-pdf-embed/dist/styles/annotationLayer.css'
import 'vue-pdf-embed/dist/styles/textLayer.css'

defineOptions({ name: 'FilePreviewDialog' })

defineProps<{
  type: 'pdf'
}>()

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 控制弹窗的显示与隐藏
const loading = ref(false) // 控制加载状态
const urlOriginal = ref('') // 原始文件地址
const url = ref('')

const handleFileJson = async (fileJson: string) => {
  loading.value = true
  try {
    let uri = ''
    const json = JSON.parse(fileJson)
    // 判断是否是数组
    if (Array.isArray(json) && json[0].url) {
      uri = json[0].url
    }
    // 判断是否为对象
    if (typeof json === 'object' && json.url) {
      uri = json.url
    }
    // 判断是否相同
    if (!uri || uri === urlOriginal.value) {
      loading.value = false
      return
    }
    url.value = ''
    urlOriginal.value = uri
    const response = await fetch(urlOriginal.value)
    const blob = await response.blob()
    if (blob.type === 'application/json') {
      message.error(t('fileObjectDownload.error'))
      return
    }
    url.value = URL.createObjectURL(blob)
  } catch {
    message.error(t('fileObjectDownload.error'))
  }
  loading.value = false
}

const open = (fileJson: string) => {
  dialogVisible.value = true
  handleFileJson(fileJson)
}

defineExpose({
  open
})
</script>

<style scoped lang="scss"></style>
